<?php

/**
 * voucher actions.
 *
 * @package    tinystockmis
 * @subpackage voucher
 * @author     Linfeng Wu
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class voucherActions extends sfActions
{

    public function preExecute()
    {

        //$this->redirectUnless($this->getUser()->isAuthenticated(), crossLinkApp::cross_app_link_to("home", "@homepage"));
        //get the current set取当前的账套
        $this->current_set = Doctrine::getTable("AcctSet")->getCurrentset();

    }

    public function executeIndex(sfWebRequest $request)
    {
        //print_r(Doctrine::getTable("AcctBriefSummary")->getAllBriefSummaryTitle());
        /*
        $this->acct_vouchers = Doctrine::getTable('AcctVoucherH')
                ->createQuery('a')
                ->execute();
        */
    }

    public function executeGetVoucherList(sfWebRequest $request)
    {

        $this->pager = new sfDoctrinePager(
                "AcctVoucherH",
                $request->getParameter("rows",sfConfig::get("app_max_vouchers_per_page", 10))
        );

        $q = Doctrine::getTable("AcctVoucherH")->getVoucherQuery();
        //add opr relation

        $this->pager->setQuery($q);
        $this->pager->setPage($request->getParameter("page", 1));

        $this->pager->init();

    }



    public function executeVoucherApprove(sfWebRequest $request)
    {
        //如果是post过来的表单数据，进行提交
        if( $request->isMethod(sfRequest::POST) and $request->getPostParameter("action") == "approve")
        {
            $voucher_id = $request->getPostParameter("voucher_id");
            $this->forward404Unless($voucher = Doctrine::getTable("AcctVoucherH")->getVoucherById($voucher_id));

            $this->getResponse()->sendHttpHeaders();

            if($voucher->getIsCancelled()) {
                echo json_encode(array("result"=>"error", "msg" => "该笔凭证已被作撤消，不能再进行其它操作."));
                return sfView::NONE;
            }

            //set approve_opr and approve_date
            $voucher->setApproveOpr($this->getUser()->getAttribute("user_id"));
            $voucher->setApproveDate(date("Y-m-d"));
            $voucher->setIsApproved('1');

            
            
            /*if($voucher->save() )
            {
                $this->getResponse()->sendHttpHeaders();
                echo json_encode(array("result"=>"success", "msg" => "审核成功."));
            } else
            {
                $this->getResponse()->sendHttpHeaders();
                echo json_encode(array("result"=>"error", "msg"=>"审核失败，请重试."));
            }
            */
            $voucher->save();
            
            echo json_encode(array("result"=>"success", "msg" => "审核成功."));
            //$response = $this->getResponse();
            //$response->setContent("application/json");
            //$this->getResponse()->setContent('application/json');
            //$this->getResponse()->setContent('application/json');
            //$this->getResponse()->setContentType('application/json');
            //$this->getResponse()->setHttpHeader('Content-type','application/json');
            //$this->getResponse()->sendContent();
            return sfView::NONE;

        }
        elseif ( $request->isMethod(sfRequest::POST) and $request->getPostParameter("action") == "cancel")
        {
            $voucher_id = $request->getPostParameter("voucher_id");
            $this->forward404Unless($voucher = Doctrine::getTable("AcctVoucherH")->getVoucherById($voucher_id));
            
            $this->getResponse()->sendHttpHeaders();

            if($voucher->getIsApproved()) {
                echo json_encode(array("result"=>"error", "msg" => "该笔凭证已通过审核，不能再进行撤消."));
                return sfView::NONE;
            }
            //set approve_opr and approve_date
            $voucher->setCancelOpr($this->getUser()->getAttribute("user_id"));
            $voucher->setCancelDate(date("Y-m-d"));
            $voucher->setIsCancelled('1');

            

            /*
            if($voucher->save())
            {
                $this->getResponse()->sendHttpHeaders();
                echo json_encode(array("result"=>"success", "msg" => "撤消成功."));
            } else
            {
                $this->getResponse()->sendHttpHeaders();
                echo json_encode(array("result"=>"error", "msg"=>"撤消失败，请重试."));
            }
            */
            $voucher->save();
            //$this->getResponse()->sendHttpHeaders();
            echo json_encode(array("result"=>"success", "msg" => "撤消成功."));
            
            return sfView::NONE;
        }

    }

    public function executeVoucherPost(sfWebRequest $request)
    {
        if($request->isMethod(sfRequest::POST) and $request->getPostParameter("action") == "post" ) {
            //进行过账处理
            $voucher_id = $request->getPostParameter("voucher_id");
            $this->forward404Unless($voucher = Doctrine::getTable("AcctVoucherH")->getVoucherById($voucher_id));

            $this->getResponse()->sendHttpHeaders();

            //检查是否已过账
            if($voucher->getIsPosted()) {
                echo json_encode(array("result"=>"error", "msg" => "该笔凭证已过账。"));
                return sfView::NONE;
            }

            //检查是否已通过审核
            if(! $voucher->getIsApproved()) {
                echo json_encode(array("result"=>"error", "msg" => "该笔凭证未经过审核，无法过账."));
                return sfView::NONE;
            }
            
            //过账处理
            if(Doctrine::getTable("AcctVoucherH")->Posting($voucher) )
            {
                echo json_encode(array("result"=>"success", "msg" => "该笔凭证已成功过账."));
                return sfView::NONE;
            }
            


            
        }

        //显示过账页面
        

    }

    public function executeGetNeedApproveVoucherList(sfWebRequest $request)
    {

        $this->pager = new sfDoctrinePager(
                "AcctVoucherH",
                $request->getParameter("rows", sfConfig::get("app_max_vouchers_per_page", 10))
        );

        $q = Doctrine::getTable("AcctVoucherH")->getVoucherQuery();
        //未被审核未被取消
        $q->addWhere("is_cancelled <> ?", 1)
                ->addWhere("is_approved <> ?", 1);

        $this->pager->setQuery($q);
        $this->pager->setPage($request->getParameter('page',1));

        $this->pager->init();
    }

    public function executeGetNeedPostVoucherList(sfWebRequest $request)
    {
        $this->pager = new sfDoctrinePager(
                "AcctVoucherH",
                $request->getParameter("rows", sfConfig::get("app_max_vouchers_per_page", 10))
        );

        $q = Doctrine::getTable("AcctVoucherH")->getVoucherQuery();
        $q->addWhere("is_cancelled <> ? ",1 )
                ->addWhere("is_approved = ? ", 1)
                ->addWhere("is_posted <> ?", 1);

        $this->pager->setQuery($q);
        $this->pager->setPage($request->getParameter("page", 1));

        $this->pager->init();
        
    }

    public function executeGetVoucherD(sfWebRequest $request)
    {

        $voucher_id = $request->getParameter("id");
        $this->vouchers = Doctrine::getTable("AcctVoucherD")->getVoucherDetailByVoucherId($voucher_id);

    }

    public function executeNew(sfWebRequest $request)
    {
        //get the account summary from db
        //$summary_title = Doctrine::getTable("AcctBriefSummary")->getAllBriefSummaryTitle();
        //取当前账套 20100411 已移至preExecute函数中

        //$this->summary_title = $summary_title;

        //$this->summary_title = json_encode($summary_title);
        //$this->summary_title = "\"" . implode("\",\"", $summary_title) . "\"";
        //$this->form = new AcctVoucherForm();

    }

    /* 该功能已经移至ajax中,由api应用实现
    public function executeGetSummary(sfWebRequest $request) {
        $summary_title = Doctrine::getTable("AcctBriefSummary")->getAllBriefSummaryTitle();

        echo json_encode($summary_title);
        return sfView::NONE;

    }
     * 
    */

    public function executeCreate(sfWebRequest $request)
    {
        $this->forward404Unless($request->isMethod(sfRequest::POST));

        //$this->form = new AcctVoucherForm();

        //$this->processForm($request, $this->form);

        //$this->setTemplate('new');
        //print_r($request->getParameterHolder()->getAll());
        $summary = $request->getPostParameter("summary");
        //print_r($summary);

        $credit = $request->getPostParameter("credit");
        $debit = $request->getPostParameter("debit");
        $subject = $request->getPostParameter("subject");

        $voucher_h = new AcctVoucherH();
        $voucher_h->setAcctSetId($this->current_set->getId());
        $acct_year = Doctrine::getTable("AcctYear")->getCurrentAcctYear($this->current_set);
        //echo "acct_year=" . $acct_year;
        $voucher_h->setAcctYear(Doctrine::getTable("AcctYear")->getCurrentAcctYear($this->current_set));
        //$voucher_h->setDate(date("Y-m-d"));
        $voucher_h->setDate($request->getPostParameter("voucher_date"));
        $voucher_h->setAcctMon(substr($request->getPostParameter("voucher_date"), 5, 2));
        $voucher_h->setOpr($this->getUser()->getAttribute("user_id"));
        $voucher_h->setDebitAmount(array_sum($debit));
        $voucher_h->setCreditAmount(array_sum($credit));
        //生成acct_voucher_d明细资料
        $voucheres = array();
        foreach($request->getPostParameter("summary") as $i => $summary)
        {
            $voucher_d = new AcctVoucherD();
            $voucher_d->setAcctSetId($this->current_set->getId());  //set Set Id
            //echo $summary[$i];
            $voucher_d->setDocSummary($summary);    //set Summary
            //set ammount
            if($debit[$i] <> 0 )
            {
                $voucher_d->setAmount($debit[$i]);
                $voucher_d->setDebitCredit('d');
            } elseif ($credit[$i] <> 0)
            {
                $voucher_d->setAmount($credit[$i]);
                $voucher_d->setDebitCredit('c');
            }
            //set Subject
            $voucher_d->setAcctSubjectId(Doctrine::getTable("AcctSubject")->getUniqueSubjectId($this->current_set,$subject[$i]));
            $voucheres[] = $voucher_d;
        }

        Doctrine::getTable("AcctVoucherH")->saveVoucher($voucher_h, $voucheres);

        //return sfView::NONE;
    }

    /*
    public function executeEdit(sfWebRequest $request) {
        $this->forward404Unless($acct_voucher = Doctrine::getTable('AcctVoucher')->find(array($request->getParameter('id'))), sprintf('Object acct_voucher does not exist (%s).', $request->getParameter('id')));
        $this->form = new AcctVoucherForm($acct_voucher);
    }
    */
    /*
    public function executeUpdate(sfWebRequest $request) {
        $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
        $this->forward404Unless($acct_voucher = Doctrine::getTable('AcctVoucher')->find(array($request->getParameter('id'))), sprintf('Object acct_voucher does not exist (%s).', $request->getParameter('id')));
        $this->form = new AcctVoucherForm($acct_voucher);

        $this->processForm($request, $this->form);

        $this->setTemplate('edit');
    }
    */

    /*
    public function executeDelete(sfWebRequest $request) {
        $request->checkCSRFProtection();

        $this->forward404Unless($acct_voucher = Doctrine::getTable('AcctVoucher')->find(array($request->getParameter('id'))), sprintf('Object acct_voucher does not exist (%s).', $request->getParameter('id')));
        $acct_voucher->delete();

        $this->redirect('voucher/index');
    }
    */
    /*
    protected function processForm(sfWebRequest $request, sfForm $form) {
        $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
        if ($form->isValid()) {
            $acct_voucher = $form->save();

            $this->redirect('voucher/edit?id='.$acct_voucher->getId());
        }
    }
    */
}
